﻿/*****************************************************************************/
/*****************************************************************************/
CREATE PROCEDURE [CaseManagement].[SaveCase]
@CaseOID            bigint          = NULL,
@CaseVersion        rowversion		= NULL,
@ServiceManID       bigint,
@CaseVolunteerID    bigint          = NULL,
@CaseDirectorID     bigint          = NULL,
@InjuryDate         datetime        = NULL

AS  

DECLARE @RetCode int,
        @RowCount int

-- 1. If new record (OID is not set)
IF ISNULL(@CaseOID, 0) <= 0 
BEGIN
	-- 1.1. Perform insert (OID is identity).
	INSERT INTO dbo.Cases
	(ServiceManID, CaseVolunteerID, CaseDirectorID, InjuryDate, UpdatedDate, CreatedDate)
	VALUES
	(@ServiceManID, @CaseVolunteerID, @CaseDirectorID, @InjuryDate, GETDATE(), GETDATE())

	-- 1.2. Determine OID of newly inserted object
	SET @CaseOID = SCOPE_IDENTITY()
END

-- 2. If OID is set (existing record)
ELSE
BEGIN
	-- 2.1. Attempt updating object (using both OID and timestamp for concurrency reasons)
	UPDATE dbo.Cases
	SET ServiceManID = @ServiceManID
	    ,CaseVolunteerID = @CaseVolunteerID
	    ,CaseDirectorID = @CaseDirectorID
	    ,InjuryDate = @InjuryDate
		,UpdatedDate = GETDATE()
	WHERE ((OID = @CaseOID) AND (Version = @CaseVersion))
    SELECT @RetCode = @@ERROR, @RowCount = @@ROWCOUNT
    IF (@RetCode <> 0) GOTO ExitError

	-- 2.2. If no records were found (and updated) - it means that
	-- another process had updated this record (therefore timestamp will be different)
	-- or record was deleted (OID not found)
	-- Either way, we need to raise exception
	IF @RowCount = 0
	BEGIN
		RAISERROR(99999, 16, 1, 'Case' ) --WITH LOG
		GOTO ExitError
	END
END 

---------------------------------------------------------------------------------------------------
--	Return the values to the caller
---------------------------------------------------------------------------------------------------
SELECT OID AS 'CaseOID', Version AS 'CaseVersion'
FROM dbo.Cases 
WHERE OID = @CaseOID

RETURN(0)

ExitError:
	RETURN(1)


